//
//  WHAppDelegate+WHThirdResponse.m
//  BinFengExpressOwner
//
//  Created by 邓伟浩 on 2018/10/21.
//  Copyright © 2018年 BinFeng. All rights reserved.
//

#import "WHAppDelegate+WHThirdResponse.h"
#import <AlipaySDK/AlipaySDK.h>


@implementation WHAppDelegate (WHThirdResponse)

#pragma mark - —————— 注册第三方服务 ——————
- (void)setUpWXShareService { // 微信
    [WXApi registerApp:kWXAppKey];
}

#pragma mark - —————— WXApiDelegate ——————

- (void)onResp:(NSObject *)resp {
    DLog(@"——————resp—————— %@", resp);
    
    if ([resp isKindOfClass:[PayResp class]]) {
        PayResp *payResp = (PayResp *)resp;
        NSString *payResult = [NSString stringWithFormat:@"errcode: %d", payResp.errCode];
        
        // 支付返回结果，实际支付结果需要去微信服务器端查询
        switch (payResp.errCode) {
            case 0:
                payResult = @"支付成功";
                KPostNotification(KUserInfoChange, nil);
                KPostNotification(KPayMoneySuccess, nil);
                break;
            case -1:
                payResult = @"支付结果：失败！";
                break;
            case -2:
                payResult = @"用户已经退出支付！";
                break;
            default:
                payResult = [NSString stringWithFormat:@"支付结果：失败！retcode = %d, retstr = %@", payResp.errCode, payResp.errStr];
        }
        [WHView showAlertwithTitle:nil message:payResult okAction:nil cancelAction:nil];
    }
    
}

#pragma mark - —————— Handle openURL ——————

- (void)gridResult:(NSDictionary *)resultDic {
    NSNumber *resultStatus = resultDic[@"resultStatus"];
    if (resultStatus.intValue == 9000) {
        [WHView showAlertwithTitle:nil message:@"支付成功" okAction:nil cancelAction:nil];
        KPostNotification(KUserInfoChange, nil);
        KPostNotification(KPayMoneySuccess, nil);
    } else {
        [WHView showAlertwithTitle:nil message:@"支付失败" okAction:nil cancelAction:nil];
    }
    
}

- (BOOL)handleOpenURL:(NSURL *)url {
    if ([url.host isEqualToString:@"platformId=wechat"] || [url.host isEqualToString:@"pay"] || [url.scheme isEqualToString:kWXAppKey]) {
        return [WXApi handleOpenURL:url delegate:self];
    }
    
    if ([url.host isEqualToString:@"safepay"]) { // 处理支付宝支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            DLog(@"result2 = %@", resultDic);
            [self gridResult:resultDic];
        }];
    }
    return YES;
}

// NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options {
    return [self handleOpenURL:url];
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    return [self handleOpenURL:url];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(nullable NSString *)sourceApplication annotation:(id)annotation {
    return [self handleOpenURL:url];
}


@end
